// DbTableShow.java

import java.io.IOException;
import java.io.OutputStream;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DbCon
{
	private static Connection cn = null;

	public DbCon()
	{
		connectDb();
	}
	public DbCon(String foo){}

	public void connectDb() {
		String sDbDrv=null, sDbUrl=null, sUsr="", sPwd="";
		sDbDrv = "com.mysql.jdbc.Driver";
		sDbUrl = "jdbc:mysql://db.hosting-agency.de/db0095122?autoReconnect=true";
		sUsr = "dbuser19577";
		sPwd = "1588.";

		try {
			// Select fitting database driver and connect:
			Class.forName( sDbDrv );
			cn = DriverManager.getConnection( sDbUrl, sUsr, sPwd );
			if(!cn.isClosed()){
				System.out.println("Successfully connected to " + sDbUrl);
				insertNmeaThreaded("START OF COMMUNICATION \n");
			}	
		} catch( Exception ex ) {
			System.out.println( ex );
		}	
	}

	public void insertNmea(String message){
		String	sql = null;
		Statement  st = null;
		int		rv = 0;   // return value for update statements
		try {
			st = cn.createStatement();
			SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			sql = "insert into nmea (time,message) values ('"+format.format(new Date())+"','"+message+"');";
			rv = st.executeUpdate( sql );
			if (rv==1) System.out.print("DB-OUT:    " + message);
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void insertNmeaThreaded (String message) {
		/*try{
			if(cn.isClosed()){
				System.out.println("WARNING: Connectionbroken, try to reconnect");
				//connectDb();
			}
		} catch( Exception ex ) {
			System.out.println( ex );
		}*/
		(new Thread(new insertThread(message))).start();
	}
	public static class insertThread implements Runnable {
		String message = null;
		String	sql = null;
		Statement  st = null;
		int		rv = 0;   // return value for update statements

		public insertThread(String m) {
			this.message = m;
		}

		public void run() {
			try {
				st = cn.createStatement();
				SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				sql = "insert into nmea (time,message) values ('"+format.format(new Date())+"','"+message+"');";
				rv = st.executeUpdate( sql );
				if (rv==1) System.out.print("DB-OUT-T:  " + message);
			}catch (SQLException e) {
				System.out.println("WARNING:   Not able to send data to db => lets hope for autoreconnect");
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/*finally {
		try { if( null != rs ) rs.close(); } catch( Exception ex ) {}
		try { if( null != st ) st.close(); } catch( Exception ex ) {}
		try { if( null != cn ) cn.close(); } catch( Exception ex ) {}

	}*/
	public static void main( String[] argv ){
		DbCon Con = new DbCon();
		Con.insertNmea("foobar\n");
		Con.insertNmeaThreaded("foobar threaded\n");
	}
}
